package ru.pb.dao.auth.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

import ru.pb.auth.dao.InventoryInfoDAO;
import ru.pb.global.dao.annotations.DAO;
import ru.pb.global.data.model.InventoryInfo;
import ru.pb.global.data.model.ItemInfo;
import ru.pb.global.dbc.DatabaseFactory;
import ru.pb.global.dbc.DatabaseUtils;

/**
 * @autor: Felixx
 */
@DAO(database = "MySQL")
public class InventoryInfoDAOImpl implements InventoryInfoDAO
{
	private static final Logger _log = Logger.getLogger(InventoryInfoDAOImpl.class);

	@Override
	public InventoryInfo getInventoryInfo(String acc, Connection con)
	{
		boolean needCloseConnection = con == null;

		PreparedStatement statement = null;
		ResultSet rset = null;
		InventoryInfo invi = null;

		try
		{
			if(needCloseConnection)
				con = DatabaseFactory.getInstance().newConnection();

			statement = con.prepareStatement("SELECT * FROM items WHERE account LIKE ? AND (loc=? OR loc=?)");
			statement.setString(1, acc);
			statement.setInt(2, 0);
			statement.setInt(3, 1);
			rset = statement.executeQuery();

			while(rset.next())
			{
				if(invi == null)
					invi = new InventoryInfo();

				int itemId = rset.getInt("item_id");
				int itemType = rset.getInt("item_type");
				int count = rset.getInt("count");
				int loc = rset.getInt("loc");
				int loc_slot = rset.getInt("loc_slot");
				int lifeTime = rset.getInt("life_time");
				int flags = rset.getInt("flags");

				invi.addItemInfo(new ItemInfo(itemId, itemType, count, loc, loc_slot, lifeTime, flags));
			}
		}
		catch(Exception e)
		{
			_log.info("Exception: " + e, e);
		}
		finally
		{
			if(needCloseConnection)
				DatabaseUtils.closeConnection(con);
			DatabaseUtils.closeDatabaseSR(statement, rset);
		}
		return invi == null ? new InventoryInfo() : invi;
	}
}